import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbjob, tbjobpublish, tbstudent } from '../../../../atoms/db';

const logger = anylogger('pages/api/zllweapp/zuoyepiyue/s002.api');

export type Result = {
	ok: true;
	students: Pick<ITbstudent, 'name' | 'student_id'>[];
	polishstudent_approved: Pick<ITbjob, 'studentname' | 'approvedlogo' | 's_jobcontext' | 'sjob_id'>[];
	polishstudent_approved2: Pick<ITbjob, 'studentname' | 's_jobcontext' | 'approvedlogo' | 'sjob_id'>[];
	count: number;
	count1: number;
} | {
	ok: false;
	message: string;
};

export type Message = {
	id: string;
}

/**
 * pages/api/zllweapp/zuoyepiyue/s002.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { id } = req.body as Message;
		/**由班级id查出本班学生 */
		const students = await tbstudent().select('name', 'student_id').where({
			class_id: id
		});
		/**对象转换字符串 */
		const studentid = students.map((it) => {
			return it.student_id;
		});
		/**查出已批或未批的学生人数 */
		const [{ num }] = await tbjob().count('approvedlogo', { as: 'num' }).where({
			approvedlogo: 1
		});
		const count = Number(num);
		const [{ num1 }] = await tbjob().count('approvedlogo', { as: 'num1' }).where({
			approvedlogo: 2
		});
		const count1 = Number(num1);

		/**查出待批学生显示 */
		const polishstudent_approved = await tbjob().select('studentname', 'approvedlogo', 's_jobcontext', 'sjob_id'
		).whereIn(
			'student_id', studentid
		).andWhere({
			approvedlogo: 1
		});
		const polishstudent_approved2 = await tbjob().select('studentname', 'approvedlogo', 's_jobcontext', 'sjob_id'
		).whereIn(
			'student_id', studentid
		).andWhere({
			approvedlogo: 2
		});


		res.status(200).json({ ok: true, students, polishstudent_approved, polishstudent_approved2, count, count1, });

	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
